<template>
  <el-dialog
    class="eldialog"
    :visible.sync="visible"
    :title="title"
    :close-on-click-modal="false"
    width="40%"
    top="2vh"
    append-to-body
    @close="closeDialog"
    v-loading="loading"
    :close-on-press-escape="false"
  >
    <div style="height: 440px; overflow-y: auto; overflow-x: hidden">
      <el-tree
        ref="tree"
        @check-change="itemClick"
        :props="props"
        :load="loadNode"
        node-key="id"
        :default-checked-keys="checkedId"
        lazy
        show-checkbox
      >
      </el-tree>
    </div>
    <template slot="footer">
      <el-button type="success" size="medium" @click="onSubmit">保存</el-button>
      <el-button type="danger" size="medium" @click="visible = false"
        >取消</el-button
      >
    </template>
  </el-dialog>
</template>
  
  <script>
import VJstree from "vue-jstree";
import {
  updateRoleSetDept,
  getRoleDepts,
} from "@/api/datacentersg/achives/documentApi";
import { saveAssignRole } from "@/api/young/system/role/role.js";
import { getTreeByRole } from "@/api/young/datacenter/person.js";
import { rejects } from "assert";

export default {
  name: "ModuleTree",
  components: {
    VJstree,
  },
  data() {
    return {
      title: "权限组维护",
      visible: false,
      roleId: "",
      valid: "",
      dataForm: {
        roleId: "",
        semiId: [],
      },
      props: {
        label: "name",
        children: "zones",
        isLeaf: "leaf",
      },
      roleGroups: [],
      treeData: [],
      defaultProps: {
        label: "label",
        children: "children",
        parentId: "parentId",
        id: "id",
      },
      // 默认选中的
      checkedId: [],
      // 默认展开
      defaultCheckedId: [],
      loading: false,
      data: [],
      nodeId: "",
      getRoleDeptsData: [],
      depId: "",
    };
  },
  methods: {
    async initItemPermissions(params) {
      this.articlesData = null;
      const that = this;
      that.roleId = "";
      // eslint-disable-next-line no-unused-vars
      const dataChange = [];
      that.roleId = params.roleId;
      this.visible = true;
      // this.initGetRoleDepts()
    },
    initGetRoleDepts(params) {
      return new Promise((resolve, reject) => {
        const paramsNew = {
          roleId: this.roleId,
        };
        getRoleDepts(paramsNew).then((result) => {
          if (result.code == 0) {
            this.getRoleDeptsData = result.data.res_data;
            resolve(this.getRoleDeptsData);
          }
        });
      });
    },
    loadNode(node, resolve) {
      console.log(node, "node");
      if (
        Array.isArray(this.getRoleDeptsData) &&
        this.getRoleDeptsData.length <= 0
      ) {
        this.initGetRoleDepts().then((res) => {
          // 第一次加载需要等待 选择的数据接口请求完成以后才，调用全部数据
          // 再 判断是否有需要回显对勾的
          this.getAllTree(node).then((res) => {
            let list = res.map((e) => {
              let checked = false;
              this.getRoleDeptsData.forEach((item) => {
                this.checkedId.push(item.deptId);
              });
              return {
                ...e,
                checked,
              };
            });
            this.setChildNodeChecked(node, 100);
            resolve(list);
          });
        });
      } else {
        // 已经获取到 已经选择的数据了，直接加载更新的数据，判断是否有需要回显对勾的
        this.getAllTree(node).then((res) => {
          let list = res.map((e) => {
            let checked = false;

            this.getRoleDeptsData.forEach((item) => {
              this.checkedId.push(item.deptId);
            });
            return {
              ...e,
              checked,
            };
          });
          this.setChildNodeChecked(node, 100);
          resolve(list);
        });
      }
    },

    setChildNodeChecked(node, time) {
      setTimeout(() => {
        let count = 0;
        node.childNodes &&
          node.childNodes.forEach((cell) => {
            if (!this.checkedId.find((val) => val == cell.data.id)) {
              count += 1;
              cell.checked = false;
              //本来想的是如果子节点有不选中的就给父节点添加半选
            } else {
              cell.checked = cell.checked;
            }
          });
        if (count != 0 && node.childNodes.length != count) {
          node.checked = false;
          node.indeterminate = true;
        }
      }, time);
    },

    itemClick(node) {
      console.log("item", node);
    },

    getAllTree(node) {
      return new Promise((resolve, reject) => {
        this.nodeId = node.id;
        let params;
        if (node.level == 0) {
          // 获得parentId = -1 的树
          params = {
            roleId: this.roleId,
            parentId: "-1",
          };
        } else {
          params = {
            roleId: this.roleId,
            parentId: node.data.id,
          };
        }
        getTreeByRole(params)
          .then((data) => {
            if (data.resultdata.length > 0) {
              resolve(data.resultdata);
            } else {
              resolve([]);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 表单提交
    async onSubmit() {
      //更新用户的保存状态机制
      const res = this.$refs.tree.getCheckedNodes(); // getCheckedNodes(false, true) 第一个参数 是否只获取叶子结点，第二个参数：当父节点下不全选的时候，也获取父节点的id
      res.forEach((item) => {
        this.depId = item.id;
      });
      const params = [];

      this.getRoleDeptsData = [];
      if (this.getRoleDeptsData.length > 1) {
        this.getRoleDeptsData.forEach((item) => {
          params.push({
            deptId: item.depId,
            roleId: this.roleId,
          });
        });
      } else {
        res.forEach((items) => {
          params.push({
            deptId: items.id, //机构id
            roleId: this.roleId, //角色id
          });
        });
      }
      updateRoleSetDept(params).then((reslut) => {
        if (reslut.code == 0) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          this.visible = false;
        }
      });
    },
    //关闭弹框的事件
    closeDialog() {
      this.visible = false;
      this.$emit("onAddSuccess", this.visible);
    },
  },
};
</script>
  
  <style scoped></style>
  